﻿using Developer.Core.FrameWork.Common.Users.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Developer.Core.FrameWork.Common.Users.Binder
{
    /// <summary>
    /// 系统用户模型绑定（从HttpContext header中获取用户信息）
    /// 1、将HttpContext用户信息转换成SysUser
    /// 2、将SysUser信息绑定到action方法参数
    /// </summary>
    public class SysUserHeaderModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
                throw new ArgumentNullException(nameof(bindingContext));

            if (bindingContext.ModelType == typeof(SysUser))
            {
                // 1、创建用户对象
                SysUser sysUser = new SysUser();

                // 2、设置模型值（cookie，header）
                HttpContext httpContext = bindingContext.HttpContext;
                IHeaderDictionary headers = httpContext.Request.Headers;

                string UserId = headers["UserId"];
                string UserName = headers["UserName"];

                // 3、判断UserId是否为空
                if (string.IsNullOrWhiteSpace(UserId))
                    throw new ArgumentNullException("授权失败，没有登录");

                sysUser.UserId = Convert.ToString(UserId);
                sysUser.UserName = Convert.ToString(UserName);

                // 4、返回结果
                bindingContext.Result = ModelBindingResult.Success(sysUser);
            }

            return Task.CompletedTask;
        }
    }
}
